package com.mic.yzzn.plc.common.instructions.response;

import com.mic.yzzn.plc.common.instructions.basic.PLCResponseInstruction;
import com.mic.yzzn.plc.common.toolUtils.PLCContactorCode;
import com.mic.yzzn.plc.common.toolUtils.PLCDataCode;
import org.apache.commons.lang.StringUtils;

/**
 * Created by ASH on 16/3/7.
 */
public class PLCSingleReadResponseInstruction extends PLCResponseInstruction
{
	/** 触点数据 */
    protected String contactorData;

    public void setContactorData(String contactorData) {
        this.contactorData = contactorData;
    }

    // 初始化方法
    public PLCSingleReadResponseInstruction()
    {
        new PLCResponseInstruction();

        instructionTypeCode = PLCResponseInstruction.PLCInstructionTypeResponseCode;
        responseCode = PLCResponseInstruction.READ_RESPONSE_CODE;
        contactorData = PLCDataCode.CONTACTOR_STATE_OFF;
    }

    public String getContactorData()
    {
        return contactorData;
    }

    @Override
    protected int getXORByBit()
    {
        int i = 0;
        int result = 0;
        for (i = 0; i < contactorData.length(); ++i)
        {
            result ^= contactorData.charAt(i);
        }

        return super.getXORByBit() ^ result;
    }

    @Override
    public String toString()
    {
        // 拼接指令字符串
        StringBuffer buffer = new StringBuffer();
        buffer.append(instructionHeader);
        buffer.append(locationNumber_high);
        buffer.append(locationNumber_low);
        buffer.append(instructionTypeCode);
        buffer.append(responseCode);
        buffer.append(contactorData);
        buffer.append(getBBC_high());
        buffer.append(getBBC_low());
        buffer.append(instructionEnd);

        return buffer.toString();    
     }
    
    @Override
    public String initWithString(String instructionString) throws IllegalArgumentException
    {
    	String tempResult = super.initWithString(instructionString);
//    	System.out.println(tempResult);
    	
    	// 检测是否已经出错
    	if (tempResult.length() == 0)
		{
			return tempResult;
		}
    	
    	int responseCodeLength = responseCode.length();
    	if (!tempResult.substring(0, responseCodeLength).equals(responseCode))
		{
			throw new IllegalArgumentException("PLCSingleReadResponseInstruction's response code must be \"" + responseCode + "\"");
		}
    	// 截断响应码
    	tempResult = StringUtils.substringAfter(tempResult, responseCode);
//    	System.out.println(tempResult);

    	if (!tempResult.equals(PLCContactorCode.PLC_CONTACTOR_OFF) &&
    			!tempResult.equals(PLCContactorCode.PLC_CONTACTOR_ON))
		{
			throw new IllegalArgumentException("contactor data's format must be \"1\" or \"0\"");
		}
    	
    	// 设置触点数据
    	contactorData = tempResult;
    	
    	// 截断触点数据
    	tempResult = StringUtils.substringAfter(tempResult, contactorData);
    	
    	return tempResult;
    }
}
